package autoorder.zsxmlv.service;

import common.zsxmlv.utils.Utils;
import common.zsxmlv.vo.Result;
import common.zsxmlv.vo.im.Message;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: ZSXM
 * @Description:
 * @Company: DingZheng
 * @Date: Create by 2018/6/9 12:33
 * @Version: 1.0
 * @Modify by:
 */
@Component
@ServerEndpoint(value = "/websocket", configurator = SpringConfigurator.class)
public class WebSocket {



    @Resource
    private TaskService taskService;

    @Resource
    private SeleniumService seleniumService;

    private static int onLineCount = 0;

    public static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        try {
            Message message = new Message();
            message.setMsg("系统就绪中");
            // 状态栏
            message.setMsgType(1);
            JSONObject object = JSONObject.fromObject(message);
            this.sendMessage(object.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnLineCount();
        System.out.println(Utils.getTime() + "  onClose");
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("服务端error");
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息：" + message);
        seleniumService.executeSendOrder(message);
//        seleniumService.autoSendOrder(message);
    }

    /**
     * 发送消息
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    private static synchronized void addOnLineCount() {
        onLineCount++;
    }

    private static synchronized void subOnLineCount() {
        onLineCount--;
    }

}
